package com.parktech.sun.web.controller.management.email;

import com.parktech.sun.domain.model.Constants;
import com.parktech.sun.domain.model.email.EmailSubscription;
import com.parktech.sun.domain.repository.Page;
import com.parktech.sun.domain.service.email.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * User: Think
 * Date: 11-1-28
 * Time: 上午3:47
 */
@Controller
@RequestMapping("/management/email/subscriptions")
public class EmailSubscriptionManagerController {

    private int pageSize = Constants.PAGINATION_PAGE_SIZE;

    private EmailService emailService;

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    @Autowired
    public EmailSubscriptionManagerController(EmailService emailService) {
        this.emailService = emailService;
    }

    @RequestMapping(value = "/search", method = RequestMethod.DELETE)
    public String delete(@RequestParam("emailSubscriptionIds") Long[] emailSubscriptionIds) {
        emailService.deleteAll(emailSubscriptionIds);
        return "redirect:search";
    }

    @RequestMapping(value = "/search", method = {RequestMethod.GET, RequestMethod.POST})
    public String search(@ModelAttribute EmailSubscriptionSearchForm emailSubscriptionSearchForm, Model model) {

        Page page = new Page(pageSize, emailSubscriptionSearchForm.getPageNo());

        model.addAttribute(
                emailService.search(
                        emailSubscriptionSearchForm.getEmailLike(), page));
        return "management/email/subscriptionSearch";
    }

    @RequestMapping("/save")
    public @ResponseBody String save(@RequestParam("id") Long id, @RequestParam("email") String email) {
        EmailSubscription emailSubscription = emailService.getById(id);
        emailSubscription.setEmail(email);
        emailService.saveOrUpdateBean(emailSubscription);
        return "success";
    }
}
